package com.itita.ww2.game.user;

import org.apache.commons.lang.StringUtils;

import com.itita.ww2.data.PlayerConfig;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.model.worldmap.UserUnlockDataMgr;
import com.itita.ww2.redis.RedisUtil;
import com.itita.ww2.redis.cache.Table;
import com.itita.ww2.utils.DataUtil;

/**
 * 玩家的世界地图数据管理器
 * @author NorthLan
 *
 */
public class UserWorldMapManager {

	private UserProfile userProfile;
	private int uid;
	private Table table;
	// 
	private UserUnlockDataMgr userUnlockData;

	public UserWorldMapManager(UserProfile userProfile) {
		this.userProfile = userProfile;
		this.uid = this.userProfile.getUid();
		this.table = UserService.getInstance().getCacheWMUserDataTable();
		this.userUnlockData = new UserUnlockDataMgr(userProfile, table);
	}

	/**
	 * 添加据点占领次数
	 */
	public void addBaseOccTimes() {
		int now = getBaseOccTimes();
		if (now == -1) {
			now = 0;
		}
		setBaseOccTimes(++now);
	}

	/**
	 * 添加据点防守成功次数
	 */
	public void addBaseDefTimes() {
		int now = getBaseDefTimes();
		if (now == -1) {
			now = 0;
		}
		setBaseDefTimes(++now);
	}

	public void baseCountOper(int value) {
		int now = getBaseCount();
		if (now == -1) {
			now = 0;
		}
		now += value;
		now = now < 0 ? 0 : now;
		setBaseCount(now);
	}

	public UserUnlockDataMgr getUserUnlockDataMgr() {
		return this.userUnlockData;
	}

	private boolean isInit() {
		String data = table.getValue(RedisUtil.genericKey(userProfile.getUid()), "unlockData");
		return StringUtils.isNotBlank(data) && !data.equals("null");
	}

	public void initialize() {
		if (!isInit()) {
			this.userUnlockData.initialize(PlayerConfig.getWMInitUnlockData());
			this.setBaseOccTimes(PlayerConfig.getWMInitBaseOccTimes());
			this.setBaseDefTimes(PlayerConfig.getWMInitBaseDefTimes());
			this.setBaseCount(PlayerConfig.getWMInitBaseCount());
		}
	}

	////////////////////////////
	private int getBaseOccTimes() {
		return DataUtil.intValueOf(table.getValue(RedisUtil.genericKey(this.uid), "base_occTimes"));
	}

	private void setBaseOccTimes(int val) {
		table.setValue(RedisUtil.genericKey(this.uid), "base_occTimes", val);
	}

	private int getBaseDefTimes() {
		return DataUtil.intValueOf(table.getValue(RedisUtil.genericKey(this.uid), "base_defTimes"));
	}

	private void setBaseDefTimes(int val) {
		table.setValue(RedisUtil.genericKey(this.uid), "base_defTimes", val);
	}

	private int getBaseCount() {
		return DataUtil.intValueOf(table.getValue(RedisUtil.genericKey(this.uid), "base_count"));
	}

	private void setBaseCount(int val) {
		table.setValue(RedisUtil.genericKey(this.uid), "base_count", val);
	}
}